import './canvas.scss'
class PieBar {
    constructor(canvasId, percent) {
        this.canvasId = canvasId
        this.percent = percent
        this.ctx = null
        this.lineWidth = 10
        this.cachePercent = 0
        this.stepTotal = 60
    }

    getDiffStep() {
        return this.percent / this.stepTotal
    }

    draw(isAni = false) {
        const diffStep = this.getDiffStep()

        const canvas = document.getElementById(this.canvasId)
        console.log('%c [ draw ]-10', 'font-size:13px; background:pink; color:#bf2c9f;', canvas)
        if (!canvas?.getContext) return console.error('浏览器不支持')

        this.ctx = canvas.getContext('2d')

        // 进度条背景
        this.ctx.beginPath()
        this.ctx.lineWidth = this.lineWidth
        this.ctx.strokeStyle = '#ddd'
        this.ctx.arc(250, 250, 240, 0, Math.PI * 2, true)
        this.ctx.stroke()

        // 进度条
        const drawBar = () => {
            if (isAni) {
                this.cachePercent += diffStep
                this.ctx.clearRect(0, 0, 500, 500)
                this.ctx.beginPath()
                const curRad = Math.PI * 2 * this.cachePercent + Math.PI * 1.5
                this.ctx.lineWidth = this.lineWidth
                this.ctx.strokeStyle = '#42bda2'
                this.ctx.arc(250, 250, 240, Math.PI * 1.5, curRad, false)
                this.ctx.lineJoin = 'round'
                this.ctx.stroke()
                if (this.cachePercent > this.percent) return

                window.requestAnimationFrame(drawBar)
            } else {
                this.ctx.beginPath()
                const curRad = Math.PI * 2 * this.percent + Math.PI * 1.5
                this.ctx.lineWidth = this.lineWidth
                this.ctx.strokeStyle = '#42bda2'
                this.ctx.arc(250, 250, 240, Math.PI * 1.5, curRad, false)
                this.ctx.stroke()
            }
        }
        drawBar()
    }
}
export default function () {
    const bar = new PieBar('canvas', 0.6)
    bar.draw(true)
}
